package mgodb

import (
	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/service/mongo"
	"jgt-oper/src/util"
	"time"
)

// cFrequentlyVisitor 常用访客表名
const cFrequentlyVisitor = "oper_frequently_visitor"

// FrequentlyVisitor 企业管理员常用访客管理
type FrequentlyVisitor struct {
	DB *mongo.DB
}

// Init 初始化
func (a *FrequentlyVisitor) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db

	// 初始化mongo索引
	a.DB.C(cFrequentlyVisitor, func(c *mgo.Collection) error {
		c.EnsureIndex(mgo.Index{
			Key:    []string{"record_id"},
			Unique: true,
		})
		c.EnsureIndexKey("user_id")
		c.EnsureIndexKey("deleted")
		return nil
	})

	var val model.IFrequentlyVisitor = a
	g.Provide(&inject.Object{Value: val, Name: "IFrequentlyVisitor"})
}

//
//func (a *FrequentlyVisitor) Create(item *schema.FrequentlyVisitor) error {
//	err := a.DB.C(cFrequentlyVisitor, func(c *mgo.Collection) error {
//		id, err := a.DB.IncrID(cFrequentlyVisitor)
//		if err != nil {
//			return err
//		}
//		item.ID = id
//		return c.Insert(item)
//	})
//	if err != nil {
//		return errors.Wrapf(err, "创建数据发生错误")
//	}
//
//	return nil
//}

// Update 更新数据
func (a *FrequentlyVisitor) Update(userID string, info map[string]interface{}) error {
	err := a.DB.C(cFrequentlyVisitor, func(c *mgo.Collection) error {
		return c.Update(bson.M{"user_id": userID, "deleted": 0}, bson.M{"$set": info})
	})
	if err != nil {
		return errors.Wrapf(err, "更新数据发生错误")
	}
	return nil
}

// Insert 插入常用访客信息(名字、电话)
func (a *FrequentlyVisitor) Insert(userID string, fv *schema.FrequentlyItem) error {
	//	检查是否初始化
	item := new(schema.FrequentlyVisitor)
	err := a.DB.C(cFrequentlyVisitor, func(c *mgo.Collection) error {
		return c.Find(bson.M{"user_id": userID, "deleted": 0}).One(item)
	})
	if err != nil && err != mgo.ErrNotFound {
		return errors.New("检查初始化出错")
	}
	if err == mgo.ErrNotFound {
		fv := new(schema.FrequentlyVisitor)
		fv.ID = 0
		fv.RecordID = util.UUID()
		fv.UserID = userID
		fv.Status = 1
		fv.Creator = userID
		fv.Created = time.Now().Unix()
		fv.Deleted = 0
		err := a.DB.C(cFrequentlyVisitor, func(c *mgo.Collection) error {
			id, err := a.DB.IncrID(cFrequentlyVisitor)
			if err != nil {
				return err
			}
			item.ID = id
			return c.Insert(item)
		})
		if err != nil {
			return errors.Wrapf(err, "常用来访初始化发生错误")
		}
	}

	err = a.DB.C(cFrequentlyVisitor, func(c *mgo.Collection) error {
		return c.Update(bson.M{"user_id": userID, "deleted": 0}, bson.M{"$addToSet": bson.M{"frequently_items": fv}})
	})
	if err != nil {
		return err
	}

	return nil
}

// Get 获取详情
func (a *FrequentlyVisitor) Get(userID string) (*schema.FrequentlyVisitor, error) {
	item := new(schema.FrequentlyVisitor)
	err := a.DB.C(cFrequentlyVisitor, func(c *mgo.Collection) error {
		return c.Find(bson.M{"user_id": userID, "deleted": 0}).One(item)
	})
	if err != nil {
		return nil, err
	}
	return item, nil
}
